package com.gin.kotlin.gf2gamecommunity.pagingsource

import android.util.Log
import com.gin.kotlin.form.PageForm
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.base.livedata.AbstractPagingSource
import com.gin.kotlin.response.theme.ThemeInfo
import retrofit2.await

class ThemePagingSource(private val size: Int = 10) : AbstractPagingSource<ThemeInfo>() {
    private val cachedData = hashMapOf<Int, ThemeInfo.List>()


    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ThemeInfo> {
        val page = params.key ?: 1
        val cache = cachedData[page]
        if (cache != null) {
            Log.i(TAG, "缓存命中: page = $page")
            return handleResponse(cache, page)
        }
        try {
            val response = App.INSTANCE.api.themeApi.getThemeList(PageForm(pageNum = page, pageSize = size)
            ).await().data ?: return LoadResult.Page(listOf(), null, null)

            cachedData[page] = response
            return handleResponse(response, page)
        } catch (e: Exception) {
            e.printStackTrace()
            return LoadResult.Error(e)
        }
    }

    private fun handleResponse(response: ThemeInfo.List, page: Int): LoadResult<Int, ThemeInfo> =
        LoadResult.Page(response.themeList, null, if (page * size < response.totalCount) page + 1 else null)

    companion object {
        private val TAG = ThemePagingSource::class.java.simpleName
    }
}